package com.traffic.visim.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.traffic.visim.kafkamq.constant.KafkaConstant;
import com.traffic.visim.kafkamq.register.KafkaProducer;
import com.traffic.visim.log.mapper.PermissionIpMapper;

import com.traffic.visim.onvif.dto.ImageInfo;
import com.traffic.visim.onvif.dto.OnvifDto;
import com.traffic.visim.onvif.entity.OnvifEvent;
import com.traffic.visim.onvif.dto.PtzRequest;
import com.traffic.visim.onvif.service.OnvifEventService;
import com.traffic.visim.service.OnvifService;
import de.onvif.soap.OnvifDevice;
import de.onvif.soap.devices.MediaDevices;
import de.onvif.soap.devices.PtzDevices;
import lombok.extern.slf4j.Slf4j;
import org.onvif.ver10.device.wsdl.GetDeviceInformationResponse;
import org.onvif.ver10.schema.Profile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.xml.soap.SOAPException;
import java.io.File;
import java.net.ConnectException;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class OnvifServiceImpl implements OnvifService {

    @Value("${onvif.imagePath}")
    private String path;

    @Autowired
    PermissionIpMapper permissionIpMapper;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    public static String ONVIF_MONITOR_ID = "ONVIF_monitor_ip:";

    @Autowired
    private KafkaProducer kafkaProducer;

    @Autowired
    OnvifEventService onvifEventService;

    @Override
    public void movePtz(PtzRequest request) {
        try {
            String cameraIP = request.getIp(); // 摄像头的IP地址
            String username = "test"; // 访问摄像头的用户名
            String password = "test"; // 访问摄像头的密码

            // 创建ONVIF设备对象
            OnvifDevice onvifDevice = new OnvifDevice(cameraIP, username, password);
            List<Profile> profiles = onvifDevice.getDevices().getProfiles();
            Profile profile1 = profiles.get(0);
            String token = profile1.getToken();
            PtzDevices ptz = onvifDevice.getPtz();
            float x = ptz.getPosition(token).getPanTilt().getX();
            float y = ptz.getPosition(token).getPanTilt().getY();
            float z = ptz.getPosition(token).getZoom().getX();
            if (1 == request.getType() && x <= 0.99f) {
                x = x + 0.01f;
            } else if (0 == request.getType() && x >= 0.01f) {
                x = x - 0.01f;
            } else if (3 == request.getType() && y <= 0.99f) {
                y = y + 0.01f;
            } else if (2 == request.getType() && y >= 0.01f) {
                y = y - 0.01f;
            } else if (5 == request.getType() && z <= 0.99f) {
                z = z + 0.01f;
            } else if (4 == request.getType() && z >= 0.01f) {
                z = z - 0.01f;
            }
            ptz.absoluteMove(token, x, y, z);
        } catch (ConnectException e) {
            throw new RuntimeException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PtzRequest getPtz(String ip) {
        PtzRequest request = PtzRequest.builder().ip(ip).build();
        try {
            String cameraIP = ip; // 摄像头的IP地址
            String username = "test"; // 访问摄像头的用户名
            String password = "test"; // 访问摄像头的密码

            // 创建ONVIF设备对象
            OnvifDevice onvifDevice = new OnvifDevice(cameraIP, username, password);
            List<Profile> profiles = onvifDevice.getDevices().getProfiles();
            Profile profile1 = profiles.get(0);
            String token = profile1.getToken();
            PtzDevices ptz = onvifDevice.getPtz();

        } catch (ConnectException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return request;
    }

    /***
     * 发送信息
     * @param ip
     * @param status
     */
    @Override
    public void sendEvent(String ip, Integer status) {
        String rtspUrl = "rtsp://test:test@" + ip + "/onvif-media/media.amp";
        String imageName = System.currentTimeMillis() + ".jpg";
        String fileName = path + File.separator + imageName;
        try {
            Thread.sleep(100);
            //VideoUtils.getVideoImagePathByRSTP(rtspUrl,fileName);
            //kafkaProducer.send(KafkaConstant.KAFKA_TRAFFIC_TOPIC,"image",JSON.toJSONString(info));
            String command = "ffmpeg -rtsp_transport tcp -i \"rtsp://test:test@" + ip + "/onvif-media/media.amp?profile=profile_1_h264&sessiontimeout=60&streamtype=unicast\" -f image2 -frames:v 1 " + fileName;
            Process process = Runtime.getRuntime().exec(command);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        OnvifEvent event = OnvifEvent.builder().createTime(new Date()).type(status)
                .ip(ip).url(imageName).build();
        log.info("进入保存摄像头数据方法{}", JSON.toJSONString(event));
        onvifEventService.saveOnvif(event);
    }

    @Override
    public void saveOnvif(String ip) {
        try {
            String cameraIP = ip; // 摄像头的IP地址
            String username = "test"; // 访问摄像头的用户名
            String password = "test"; // 访问摄像头的密码
            log.info("ip is {}", ip);
            // 创建ONVIF设备对象
            OnvifDevice onvifDevice = new OnvifDevice(cameraIP, username, password);
            // 获取设备信息
            GetDeviceInformationResponse deviceInfoResponse = onvifDevice.getDevices().getDeviceInformation();

            String manufacturer = deviceInfoResponse.getManufacturer();
            String model = deviceInfoResponse.getModel();
            String firmwareVersion = deviceInfoResponse.getFirmwareVersion();
            String serialNumber = deviceInfoResponse.getSerialNumber();

            System.out.println("Manufacturer: " + manufacturer);
            System.out.println("Model: " + model);
            System.out.println("Firmware Version: " + firmwareVersion);
            System.out.println("Serial Number: " + serialNumber);

            Profile profile = onvifDevice.getDevices().getProfiles().get(0);

            MediaDevices media = onvifDevice.getMedia();
            String url = media.getRTSPStreamUri(profile.getToken());
            OnvifDto dto = OnvifDto.builder().ip(ip).manufacture(manufacturer)
                    .hardwareId(deviceInfoResponse.getHardwareId())
                    .firmwareVersion(firmwareVersion).model(model)
                    .serialNumber(serialNumber).rtspUrl(url).build();
            stringRedisTemplate.opsForValue().set(ONVIF_MONITOR_ID + ip, JSON.toJSONString(dto));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void saveAllOnvif() {
        List<String> ipList = permissionIpMapper.getIpList();

        if (CollUtil.isNotEmpty(ipList)) {

                ipList.forEach(ip -> {
                    String cameraIP = ip; // 摄像头的IP地址
                    String username = "test"; // 访问摄像头的用户名
                    String password = "test"; // 访问摄像头的密码
                    log.info("ip is {}", ip);
                    // 创建ONVIF设备对象
                    OnvifDevice onvifDevice = null;
                    try {
                        onvifDevice = new OnvifDevice(cameraIP, username, password);
                    } catch (ConnectException | SOAPException e) {
                        throw new RuntimeException(e);
                    }
                    // 获取设备信息
                    GetDeviceInformationResponse deviceInfoResponse = onvifDevice.getDevices().getDeviceInformation();

                    String manufacturer = deviceInfoResponse.getManufacturer();
                    String model = deviceInfoResponse.getModel();
                    String firmwareVersion = deviceInfoResponse.getFirmwareVersion();
                    String serialNumber = deviceInfoResponse.getSerialNumber();

                    String url = null;
                    if (CollUtil.isNotEmpty(onvifDevice.getDevices().getProfiles()))
                    {
                        Profile profile = onvifDevice.getDevices().getProfiles().get(0);

                        MediaDevices media = onvifDevice.getMedia();


                        try {
                            url = media.getRTSPStreamUri(profile.getToken());
                        } catch (ConnectException | SOAPException e) {
                            throw new RuntimeException(e);
                        }
                    }


                    OnvifDto dto = OnvifDto.builder().ip(ip).manufacture(manufacturer)
                            .hardwareId(deviceInfoResponse.getHardwareId())
                            .firmwareVersion(firmwareVersion).model(model)
                            .serialNumber(serialNumber).rtspUrl(url).build();
                    stringRedisTemplate.opsForValue().set(ONVIF_MONITOR_ID + ip, JSON.toJSONString(dto));
                });

        }


    }

    @Override
    public void createImage(ImageInfo info) {
        try {
            Thread.sleep(100);
            //VideoUtils.getVideoImagePathByRSTP(info.getUrl(),info.getFileName());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
